package com.buddy.syn.block._08;

import java.util.ArrayList;
import java.util.List;

/**
 * 验证 多个线程调用同一个方法是随机的
 */
public class SynOutAsynService {

    private List list = new ArrayList();

    public void add(String userName) {
        System.out.println("线程名称：" + Thread.currentThread().getName()
                + "执行了add方法");
        try {
            synchronized (list) {
                if (list.size() < 1) {
                    Thread.sleep(2000);
                    list.add(userName);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程名称：" + Thread.currentThread().getName()
                + "完成了add方法");

    }

    synchronized public int getSize() {
        System.out.println("线程名称：" + Thread.currentThread().getName()
                + "执行了getSize方法");
        int size = list.size();
        System.out.println("线程名称：" + Thread.currentThread().getName()
                + "完成了getSize方法");
        return size;

    }
}
